const db=wx.cloud.database()
let that=this
Page({
  data: {
    number:1,//图片数
    Price:0,//价格
    telValue: "",//描述文字
    name:"",//商品名称
    type:"",//商品分类
    nickName: "",//用户名
    avatarUrl:"",//用户头像
    icon:"",
    address:"",
    array:['生活用品','书籍课本','外卖代取','快递代取'],
  },

  onLoad(options) {
    let userinfo=wx.getStorageSync('app.globalData.userInfo');
    this.setData({
      nickName:userinfo.nickName,
      avatarUrl:userinfo.avatarUrl
    })
  },

  onReady() {
  },

  onShow() {
  },

  getName:function(e){
  this.setData({
    name: e.detail.value
  })
},

  getInput: function (e) {
    this.setData({
      telValue: e.detail.value
    })
  }, 
  
  uploadImage(fileURL) {
    var that = this
    wx.cloud.uploadFile({
      cloudPath:new Date().getTime()+'.png', 
      filePath: fileURL, 
      success: res => {
        that.addImagePath(res.fileID)
      },
      fail: console.error
    })
  },

  addImagePath(fileId) {
    var that=this
    console.log(fileId)
    wx.cloud.getTempFileURL({
      fileList: [fileId],
      success: res => {
        that.data.icon = res.fileList[0].tempFileURL
        console.log(that.data.icon)
      },
      fail: console.error
    })
  },

  btnsub: function (res) {
    var that = this
    console.log(res)
    var Name=res.detail.value.name
    var Desc=res.detail.value.describe
    var Type=that.data.type
    var Price=res.detail.value.price
    var takePlace=res.detail.value.address
    var icon=that.data.icon
    var usern=that.data.nickName
    var userurl=that.data.avatarUrl
    var nowtime = new Date().getTime()
    var time=that.formatDate(nowtime)
    var tempFilePaths = that.data.Filepath
    if (Name!="" && Price != 0 && Type!="" && takePlace!="" && that.data.number!= 1) {
      wx.showLoading({
        title: '发布中...',
        mask:true,
        duration:1000
      }).then(res=>{
          db.collection("good").add({
            data:{
              name:Name,
              content:Desc,
              type:Type,
              address:takePlace,
              price:Price,
              time:time,
              username:usern,
              userurl:userurl,
              icon:icon
            }
          }).then(res=>{
            wx.hideLoading()
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 1000,
              success: function () {
                console.log(res)
              }
            })
            that.setData({
              name:"",
              type:"",
              telValue:"",
              address:"",
              price:"",
              icon:"",
              number:1
            })
            wx.switchTab({
              url: '../home/home'
            })            
          },)
        })
     }
     else {
      wx.showToast({
      icon: 'none',
      title: '请检查输入的数据是否有误！',
      duration: 1000,
      mask: true,
     })
   }
  },

  cancel:function(){
    wx.navigateTo({
      url:'../../pages/home'
    })
  },

  clickimage: function (e) {
    var index = e.target.dataset.index
    wx.previewImage({
      urls: [this.data.Filepath[index]], 
    })
  },

  addImage: function (e) {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log("成功",res);
        that.uploadImage(res.tempFilePaths[0]);

        that.setData({
          Filepath: res.tempFilePaths,
          number: res.tempFilePaths.length + 1
        })
      }
    })
  },

  deleteImage: function (e) {
    var that = this
    var index = e.target.dataset.index
    var tempFilePaths = that.data.Filepath
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          tempFilePaths.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          Filepath: tempFilePaths,
          number: that.data.number - 1,
          icon:""
        });
      }
    })
  },

  pickType:function(e){
    this.setData({
      type:this.data.array[e.detail.value]
    })
  },

  getPriceinput:function(e){
    this.setData({
      Price: e.detail.value
    })
  },

  formatDate: function (times) {
    var date = new Date(times);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() //获取小时
    var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();//获取分钟
    var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();//获取秒数
    return year + '-' + month + '-' + day +' '+hour+':'+minute+':'+second
},

})